using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;

namespace OpenWaves
{
    public static class MD5Hash
    {
        [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
        public static string Compute(string value)
        {
            Contract.Requires<ArgumentNullException>(value != null);
            Contract.Ensures(String.IsNullOrEmpty(Contract.Result<string>()) == false);

            byte[] bytes = Encoding.UTF8.GetBytes(value);
            byte[] hash;
            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                hash = md5.ComputeHash(bytes);
            }

            var s = new StringBuilder();
            foreach (byte b in hash)
            {
                s.Append(b.ToString("x2", CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));
            }

            return s.ToString();
        }
    }
}